/**
 * 
 */
package fr.cephb.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Base class for a Filter used to export the data
 * as XML/CSV/etc...
 *
 */
public abstract class AbstractExportFilter extends AbstractFilter
	{
	public static final String PARAM="format";

	
	@Override
	public void doFilter(ServletRequest sreq, ServletResponse sres,
			FilterChain chain) throws IOException, ServletException
		{
		if(!(sreq instanceof HttpServletRequest) ||
		   !(sres instanceof HttpServletResponse))
			{
			chain.doFilter(sreq, sres);
			return;
			}
		HttpServletRequest request =(HttpServletRequest)sreq;
		if(!isFiltering(request))
			{

			chain.doFilter(sreq, sres);
			return;
			}
		
		HttpServletResponse response= (HttpServletResponse)sres;
		ServletResponseToFile wrap= new ServletResponseToFile(response);
		chain.doFilter(sreq, wrap);
		wrap.close();

		if(wrap.getFile()==null) throw new ServletException("Filtering/Export failed");
		try {
			export(wrap.getFile(),request,response);
			} 
		catch (IOException e) {
			e.printStackTrace();
			throw e;
			}
		catch (ServletException e) {
			e.printStackTrace();
			throw e;
			}
		catch (Throwable e) {
			e.printStackTrace();
			throw new ServletException(e);
			}
		finally
			{
			if(wrap.getFile()!=null) wrap.getFile().delete();
			}
		}
	/** return wether we are filtering the ouput */
	protected abstract boolean isFiltering(HttpServletRequest req) throws ServletException;
	/** process the page that was saved in 'content'  */
	protected abstract void export(File content,HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException;
	}
